﻿using System.Collections.Generic;
using System.IO;

static class IoUtilities
{
    public static IEnumerable<string> ResolvePath(string pathPattern, string relativeBase = null)
    {
        var parts = pathPattern.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
        if (Path.IsPathRooted(pathPattern))
        {
            return ResolvePath(parts[0] + Path.DirectorySeparatorChar, parts, 1);
        }
        else
        {
            return ResolvePath(relativeBase, parts, 0);
        }
    }

    static IEnumerable<string> ResolvePath(string parentPath, IList<string> pathParts, int partIndex)
    {
        if (partIndex == pathParts.Count || (partIndex == pathParts.Count - 1 && pathParts[partIndex].Length == 0))
        {
            yield return parentPath;
            yield break;
        }

        var part = pathParts[partIndex];

        IEnumerable<string> subDirs;
        if (part == ".")
        {
            subDirs = new string[] { parentPath };
        }
        else if (part == "..")
        {
            subDirs = new string[] { Path.GetDirectoryName(parentPath) };
        }
        else
        {
            subDirs = Directory.GetDirectories(parentPath, part);
        }
        foreach (var curPath in subDirs)
        {
            var subPaths = ResolvePath(curPath, pathParts, partIndex + 1);
            foreach (var curSubPath in subPaths)
            {
                yield return curSubPath;
            }
        }
    }
}